<?php
class WorkoutsController extends AppController {
	
	var $name = 'Workouts';
	var $uses = array('Workout', 'Template', 'Period', 'Status');
	
	var $paginate = array(
		'Workout' => array(
			'limit' => 10,
			'order' => array('Workout.date' => 'asc','Workout.order' => 'asc')
		)
	);
	
	function beforeFilter() {
		parent::beforeFilter();
		
		if($this->Session->read('redirect_action') == null) {
			$this->Session->write('redirect_action','month');
		}
		
		return true;
	}

	function month($year = null, $month = null) {
		if(!is_numeric($year)) {
			$year = $header = date('Y');
		}
		
		if(!is_numeric($month)) {
			$month = date('m');
		}
		if($month < 1) $this->redirect(array('action'=>'month',$year-1, 12));
		if($month > 12) $this->redirect(array('action'=>'month', $year+1, 1));
		
		
		$date_range = $this->DateUtility->dateRangeForMonth($year, $month);
		$days = $this->DateUtility->dateArrayForMonth($year, $month);

		$header = date('F, Y', mktime(0, 0, 0, $month, 1, $year));

		$periods = $this->Period->currentPeriods($this->user['User']['id']);
		$workouts = $this->Workout->findBetweenDates($date_range[0]['date'], $date_range[1]['date']);
		$statuses = $this->Status->findBetweenDates($date_range[0]['date'], $date_range[1]['date']);
		//debug($statuses);
		//debug($workouts);
		$templates = $this->Workout->Template->find('all', array('contain'=>'Type'));
		
		$weekdays = $this->DateUtility->weekdayNames();
		$this->_mergeDateAndWorkouts($days, $workouts, $periods, $statuses);
		$this->Session->write('redirect_action',"month/$year/$month");
		$this->pageTitle = __('Workouts for', true) . ' ' . $this->user['User']['username'] . ' ' . __('in', true) . ' ' . date('F Y', mktime(0, 0, 0, $month, 1, $year));
		$this->set(compact('workouts', 'year', 'month', 'weekdays', 'days', 'templates', 'header'));
	}
	
	function index($key = 'm', $year = null, $browse = null) {
		//debug($this->Session->read('redirect_action'));
		$this->redirect($this->Session->read('redirect_action'));

	}

	function _mergeDateAndWorkouts(&$days=array(), $workouts=array(), $periods=array(), $statuses=array()) {
		if(count($workouts)>0) {
			$grouped = array();
			foreach($workouts as $workout) {
				$key = $workout['Workout']['date'];
				$grouped[$key][]=$workout;
			}
			foreach($grouped as $key => $value) {
				$days = Set::insert($days, "$key.Workouts", $value);
			}
		}
		
		if(count($statuses)>0) {
			foreach($statuses as $status) {
				$key = $status['Status']['date'];
				$days = Set::insert($days, "$key.Status", $status);
			}
		}
		//debug($days);
		
		//debug($periods);
		if(count($periods)>0) {
			$grouped = array();
			foreach($periods as $period) {
				$ts1 = $this->DateUtility->dateStringToUnix($period['Period']['start_date']);
				$ts2 = $this->DateUtility->dateStringToUnix($period['Period']['end_date']);
				reset($days);
				while ($day = current($days)) {
				    if (isset($day['ts']) and $day['ts']>=$ts1 and $day['ts']<=$ts2) {
						$key = key($days);
						//debug($key);
						$days = Set::insert($days,  "$key.Period", $period);
				    }
				    next($days);
				}
			}
		}
		//debug($days);
		
	}


	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Workout.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Workout->recursive = 2;
		$this->Workout->contain(array('Template'=>array('Type.id','Type.title', 'Ability.id','Ability.title')));
		$this->set('workout', $this->Workout->read(null, $id));
	}
	
	
	function add($date=null) {
		if (!empty($this->data)) {
			$this->Workout->create();
			$this->data['Workout']['user_id'] = $this->user['User']['id'];
			if ($this->Workout->save($this->data)) {
				$this->Session->setFlash(__('The Workout has been saved', true));
				$this->_afterSave($this->data);
			} else {
				$this->Session->setFlash(__('The Workout could not be saved. Please, try again.', true));
			}
		} else {
			if($date == null) {
				$this->data['Workout']['date'] = date('Y-m-d'); //2009-10-24
			} else {
				$this->data['Workout']['date'] = $date;
			}
			
		}
		//$users = $this->Workout->User->find('list');
		$templates = $this->Workout->Template->find('list');
		$this->set(compact('templates'));
		if($this->RequestHandler->isAjax()) {
			$ajax = "true";
			$this->set(compact('ajax'));
		}
	}
	
	function _afterSave($workout) {
		if($this->RequestHandler->isAjax()) {
			$workouts = $this->Workout->findAllByDate($workout['Workout']['date']);
			//debug($workouts);
			$this->set(compact('workouts'));
			//$this->layout = "ajax";
			$this->render('elements/day');
		} else {
			$this->redirect($this->Session->read('redirect_action'));
		}
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Workout', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Workout->save($this->data)) {
				$this->Session->setFlash(__('The Workout has been saved', true));
				$this->_afterSave($this->data);
			} else {
				$this->Session->setFlash(__('The Workout could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Workout->read(null, $id);
		}
		$users = $this->Workout->User->find('list');
		$templates = $this->Workout->Template->find('list');
		$this->set(compact('users','templates'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Workout', true));
			$this->redirect(array('action'=>'index'));
		}
		$workout = $this->Workout->read(null, $id);
		if ($this->Workout->del($id)) {
			$this->Session->setFlash(__('Workout deleted', true));
			$this->_afterSave($workout);
		}
	}
	
	/* MOVING AND COPYING RECORDS */
	
	function move($id = null, $to_day = null) {
			$object = array('message' => __('test', true));
			$workouts = $this->Workout->find('all', array('order'=>$this->paginate['Workout']['order'], 'conditions' => array('Workout.date' => $to_day)));
			$count = 1;
			$found = count($workouts);
			//debug($workouts);
			foreach($workouts as $workout_id) {
				if($workout_id != $id) {
					$this->Workout->id = $workout_id;
					$this->Workout->saveField('order', $count);
					$count++;
				}
			}
			
			
			$this->Workout->id = $id;
			$this->Workout->recursive = -1;
			$workout = $this->Workout->read(null, $id);
			$workout['Workout']['date'] = $to_day;
			$workout['Workout']['order'] = $count;
			//debug($workout);
			if($this->Workout->save($workout)) {
				$object = $workout;
			} else {
				$object = array('error' => __('Error when saving', true));
			}

		//$object = $workouts;
		$this->set(compact('object'));
		$this->render('json_get_template');
	}
	function copyweek($date, $offset) {
		$org_ts1 = $this->DateUtility->dateStringToUnix($date);
		if($org_ts1 != 0) {
			$org_ts2 = $org_ts1 + WEEK;
			
			$workouts = $this->Workout->findBetweenDates($date, date($this->DateUtility->format, $org_ts2));
			if(count($workouts) > 0) {
				$new_ts1 = $org_ts1 + (WEEK * $offset);
				$copied = 0;
				foreach($workouts as $workout) {
					$workout_ts = $this->DateUtility->dateStringToUnix($workout['Workout']['date']);
					$new_workout['Workout'] = $workout['Workout'];
					$new_workout['Workout']['id'] = null;
					$new_workout['Workout']['date'] = date($this->DateUtility->format, $new_ts1+($workout_ts - $org_ts1));
					$this->Workout->create();
					if ($this->Workout->save($new_workout)) {
						$copied++;
					}
				}
				$message = count($workouts) . ' ' . __('of', true) . ' ' . $copied . ' ' . __('workouts was copied!', true);
			} else {
				$message = __('No workouts found to copy!', true);
			}			
		} else {
			$message = __('Invalid Workout', true);
		}
		$this->Session->setFlash($message);
		$this->redirect($this->Session->read('redirect_action'));
	}
	
	/* Move to other controller */
	function json_get_template($id = null) {
		$this->Workout->Template->recursive = -1;
		$object = $this->Workout->Template->read(null, $id);
		$this->set(compact('object'));
	}

	
	/* ADMIN FUNCTIONS */
	function admin_index() {
		$this->Workout->recursive = 0;
		$this->set('workouts', $this->paginate());
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Workout.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('workout', $this->Workout->read(null, $id));
	}

	function admin_add() {
		if (!empty($this->data)) {
			$this->Workout->create();
			if ($this->Workout->save($this->data)) {
				$this->Session->setFlash(__('The Workout has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Workout could not be saved. Please, try again.', true));
			}
		}
		$users = $this->Workout->User->find('list');
		$templates = $this->Workout->Template->find('list');
		$this->set(compact('users', 'templates'));
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Workout', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Workout->save($this->data)) {
				$this->Session->setFlash(__('The Workout has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Workout could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Workout->read(null, $id);
		}
		$users = $this->Workout->User->find('list');
		$templates = $this->Workout->Template->find('list');
		$this->set(compact('users','templates'));
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Workout', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Workout->del($id)) {
			$this->Session->setFlash(__('Workout deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}

}
?>